//
//  FANRefreshControl.swift
//  Weibo - Swift
//
//  Created by user on 16/4/23.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit

enum FANRefreshControlState: Int {
    case Normal = 0//"默认"
    case Pulling = 1//"松手就去刷新的状态"
    case Refreshing = 2//"刷新中的状态"
}


let refreshControlHeight:CGFloat = 50

class FANRefreshControl: UIControl {
    
    var fanState:FANRefreshControlState = .Normal{
        
        didSet{
            
            switch fanState{
                
                case .Normal:
                
                    label.text = "下拉刷新"
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.upDownImageView.transform = CGAffineTransformIdentity
                    })
                    indicatorView.stopAnimating()
                
                    upDownImageView.hidden = false
                
                    if oldValue == .Refreshing{
                        
                        UIView.animateWithDuration(0.25, animations: { () -> Void in
                            
                            self.tableView?.contentInset.top = self.tableView!.contentInset.top - refreshControlHeight
                        })
                }
                
                case .Pulling:
                
                    label.text = "松手刷新"
                
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.upDownImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    })
                
                
                    
                case .Refreshing:
                
                    label.text = "正在加载"
                
                    upDownImageView.hidden = true
                
                    indicatorView.startAnimating()
                    
                        UIView.animateWithDuration(0.25, animations: { () -> Void in
                            
                            self.tableView?.contentInset.top = self.tableView!.contentInset.top + refreshControlHeight
                        })
                    
                    
                    sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
            }
        }
    }
    
    var tableView:UIScrollView?

    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        guard let tableView = newSuperview where tableView.isKindOfClass(UIScrollView.self) else{
            
            return
        }
        
        self.frame.size.width = tableView.frame.width
        
        self.tableView = tableView as? UIScrollView
        
        tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffsetY = tableView?.contentOffset.y
        
        let conValue = -tableView!.contentInset.top - refreshControlHeight
        
        //拽住屏幕
        if self.tableView!.dragging {
            
            //小于-114,说明拉出来了 松手即将刷新
            
            if contentOffsetY < conValue && fanState == .Normal{//&& fanState == .Normal{
                
//                print("松手即将刷新")
                
                fanState = .Pulling
            }else{
                
//                print("松手依旧默认状态")
//                                fanState = .Normal
                if contentOffsetY >= conValue && fanState == .Pulling{//&& fanState == .Pulling
                    
//                    print("松手依旧默认状态")
                    
                    fanState = .Normal
                }
//
                
            }
            
        }else{ //松手

            if fanState == .Pulling{
                
//                print("我要刷新了!")
                
                fanState = .Refreshing
            }
            
        }
        
    }
    
    deinit{
        
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    func endRefresh(){
        
        
            fanState = .Normal
        
//            print("结束刷新")
    }
    
    private func setup(){
        
        backgroundColor = UIColor.clearColor()
        
        self.frame.size.height = refreshControlHeight
        
//        self.frame.size.width = ScreenW
        
        self.frame.origin.y = -refreshControlHeight
        
        self.addSubview(upDownImageView)
        self.addSubview(label)
        self.addSubview(indicatorView)
        
        upDownImageView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self.snp_centerX).offset(-35)
            
            make.centerY.equalTo(self.snp_centerY)
        }
        
        label.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(self.snp_centerY)
            
            make.leading.equalTo(upDownImageView.snp_trailing)
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self.snp_centerX).offset(-35)
            
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
    }
    
    lazy var upDownImageView :UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    lazy var label:UILabel = {
        
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 12)
        
        label.text = "下拉刷新"
    
        return label
    }()
    
    lazy var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .White)
 
    
    
}